

function checkPhone(phone) {
    if(phone.search(/^1[3458]{1}[0-9]{9}$/) == -1)
        return false;
    else
        return true;
}

function checkTime(time) {
    if(time.search(/^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/) == -1)
        return false;
    else
        return true;
}

function formatTime(time) {
    var date = new Date(time);
    var month = (date.getMonth() + 1) < 10 ? '0'+(date.getMonth() + 1): (date.getMonth() + 1);
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    return date.getFullYear() + '-' +  month + '-' + day;
}

function checkQq(qq) {
    if(qq.search(/[1-9]\d{4,}/) == -1)
        return false;
    else
        return true;
}

var mediaEdit;
var coNotesEdit;
var uid;
var successArr = {};

var headline = {
    getData: function() {
        $.ajax({
            url: window.domain + window.requestUrl.singleInfoUrl,
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data: {
                id: window.getUrlParam('id'),
                platId: 2
            },
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }
                if(res.status) {
                    var result = res.data.result;
                    $('.form-item__avatar').prop('src', result.iconUrl);
                    $('[data-role="name"]').html(result.title);
                    $('[data-role="fans"]').html(result.fans);

                    uid = result.id;

                    var resultData = JSON.parse(result.prices);
                    if(resultData.price1 == -1) {
                        $('[data-role="ttbj"]').val('');
                    } else {
                        $('[data-role="ttbj"]').val(resultData.price1);
                    }

                    if(resultData.price2 == -1) {
                        $('[data-role="ctbj"]').val('');
                    } else {
                        $('[data-role="ctbj"]').val(resultData.price2);
                    }

                    $('[data-role="qq"]').val(result.qq);

                    var tagTpl = '';
                    var titleTags = res.data.tags;
                    $.each(JSON.parse(res.data.result.tags), function(index, item) {
                        tagTpl += '<a  href="javascript:void(0);" title="'+titleTags[item]+'"  data-id="'+item+'"><span>'+titleTags[item]+'</span><em></em></a>';
                    })
                    $('.plus-tag').html(tagTpl);

                    headline.addTag(JSON.parse(res.data.result.tags));

                    var positionData = JSON.parse(res.data.result.position);
                    if(typeof(positionData) != 'undefined') {
                        $("#citySelect").citySelect({
                            prov:positionData.province, //省份
                            city:positionData.city, //城市
                            dist:positionData.county, //区县
                            nodata:"none" //当子集无数据时，隐藏select
                        });
                    }

                    headline.getinfo();
                    headline.ueditor();
                    headline.successHandle();

                } else {
                    iosOverlay({
                        text: res.msg,
                        duration: 1000
                    });
                }
            },
            error: function(e) {
            }
        })
    },
    submit: function() {
        $(document).on('click', '[data-role="submit"]', function() {

            var qq = $('[data-role="qq"]').val();
            var $qq = $('[data-role="qq"]');
            if(qq == '' || !checkQq(qq)) {
                iosOverlay({
                    text: '请填写正确的QQ',
                    duration: 1000
                });
                return;
            }

            var ttbj = $('[data-role="ttbj"]').val();
            var $ttbj = $('[data-role="ttbj"]');
            var ctbj = $('[data-role="ctbj"]').val();
            var $ctbj = $('[data-role="ctbj"]');
            if(ttbj == '' && ctbj == '') {
                iosOverlay({
                    text: '广告植入价格和现场直播价格至少填写一项',
                    duration: 1000
                });
                return;
            }

            if($('.plus-tag a').length == 0) {
                iosOverlay({
                    text: '请选择分类标签',
                    duration: 1000
                });
                return;
            }

            if(checkQq(qq) && (ttbj != '' || ctbj != '') && $('.plus-tag a').length > 0) {
                var tagArr = [];
                $.each($('.plus-tag a'), function(index, item) {
                    tagArr.push($(item).attr('data-id'));
                })
                var obj = {
                    qq: qq,
                    price1: ttbj == '' ? -1 : ttbj,
                    price2: ctbj == '' ? -1 : ctbj,
                    tagJsonArr: tagArr,
                    positionJsonObj:{"province": $('#province').val(), "city": $('#city').val(), "county": $('#county').val()},
                };
                $.ajax({
                    url: window.domain + window.requestUrl.updatePlatInfoUrl,
                    type: 'post',
                    data: {
                        uParams: JSON.stringify(obj),
                        id: window.getUrlParam('id')
                    },
                    xhrFields: {
                        withCredentials: true
                    },
                    crossDomain: true,
                    success: function(res) {
                        if(typeof(res.not_login) != 'undefined') {
                            window.setCookie('go_back_link', window.location.href);
                            window.location.href = './login.html';
                            return;
                        }
                        if(res.status) {
                            // window.location.href = './headline-show.html';
                            iosOverlay({
                                text: '提交成功',
                                duration: 1000
                            });
                        } else {
                            iosOverlay({
                                text: res.msg,
                                duration: 1000
                            });
                        }
                    },
                    error: function(e) {
                    }
                })
            }
        })
    },
    addTag: function(taged) {
        $.ajax({
            url: window.domain + window.requestUrl.getPlatTagUrl + '2',
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }
                if(res.status) {
                    var tags = res.data.tags;
                    var tpl = '';
                    $.each(tags, function(index, item) {
                        var flag = true;

                        $.each(taged, function(indexDir, itemDir) {
                            if(item.id == itemDir) {
                                flag = false;
                            }
                        })
                        if(flag) {
                            tpl += '<a value="-1" title="'+item.tag+'" data-id="'+item.id+'" href="javascript:void(0);"><span>'+item.tag+'</span><em></em></a>';
                        } else {
                            tpl += '<a value="-1" title="'+item.tag+'" data-id="'+item.id+'" href="javascript:void(0);" class="selected"><span>'+item.tag+'</span><em></em></a>';
                        }
                    })
                    $('.default-tag .clearfix').html(tpl);
                } else {
                    iosOverlay({
                        text: res.msg,
                        duration: 1000
                    });
                }
            },
            error: function(e) {
            }
        })
    },
    ueditor: function() {
        mediaEdit = UE.getEditor('media-edit', {scaleEnabled:true});
        coNotesEdit = UE.getEditor('qwe', {scaleEnabled:true});
    },
    successHandle: function() {
        $('[data-role="addSuccess"]').on('click', function() {
            var random = Math.random();
            var tpl = '<div class="mediaLogined-main__success">\
                            <div class="form-item">\
                                <span class="form-item__name"><em>*</em>案例事件：</span>\
                                <input type="text" data-role="name">\
                                <span class="tips"></span>\
                            </div>\
                            <div class="form-item">\
                                <span class="form-item__name"><em>*</em>合作时间：</span>\
                                <input type="text" data-role="co-time">（格式: 2017-03-27）\
                                <span class="tips"></span>\
                            </div>\
                            <div class="form-item">\
                                <span class="form-item__name"><em>*</em>合作客户：</span>\
                                <input type="text" data-role="co-person">\
                                <span class="tips"></span>\
                            </div>\
                            <div class="form-item">\
                                <span class="form-item__name"><em>*</em>推广效果：</span>\
                                <input type="text" data-role="co-effect">\
                                <span class="tips"></span>\
                            </div>\
                            <div class="form-item">\
                                <span class="form-item__name">合作链接：</span>\
                                <input type="text" data-role="co-link">\
                                <span class="tips"></span>\
                            </div>\
                            <span class="form-item__name">其他说明：</span>\
                            <script id="success'+random+'" name="content" type="text/plain">\
                            </script>\
                            <div class="form-submit ext-edit" data-role="success-submit" style="clear:both;" data-success="success'+random+'">\
                                提交发布\
                            </div>\
                            <div class="form-submit  ext-edit" data-role="success-del">\
                                删除本条\
                            </div>\
                        </div>';
            $('[data-role="success-container"]').prepend(tpl);
            successArr['success' + random] = UE.getEditor('success' + random);
        })

        // 删除
        $(document).on('click', '[data-role="success-del"]', function() {
            var $this = $(this);
            var cid = $this.attr('data-cid');
            if(cid) {
                $.ajax({
                    url: window.domain + window.requestUrl.delInfoUrl + '2',
                    type: 'post',
                    xhrFields: {
                        withCredentials: true
                    },
                    crossDomain: true,
                    data: {
                        pid: Number(uid),
                        cid: Number(cid)
                    },
                    success: function(res) {
                        if(typeof(res.not_login) != 'undefined') {
                            window.setCookie('go_back_link', window.location.href);
                            window.location.href = './login.html';
                            return;
                        }
                        if(res.status) {
                            iosOverlay({
                                text: '删除成功',
                                duration: 1000
                            });
                            $this.closest('.mediaLogined-main__success').remove();
                        } else {
                            iosOverlay({
                                text: res.msg,
                                duration: 1000
                            });
                        }
                    },
                    error: function(e) {
                    }
                })
            } else {
                $this.closest('.mediaLogined-main__success').remove();
            }
        })
        //提交
        $(document).on('click', '[data-role="success-submit"]', function() {
            var $this = $(this);
            var cid = $this.attr('data-cid');
            var parent = $this.closest('.mediaLogined-main__success');

            var obj = {};
            var name = parent.find('[data-role="name"]').val();
            if(name == '') {
                iosOverlay({
                    text: '案例事件不能为空',
                    duration: 1000
                });
                return;
            }
            var time = parent.find('[data-role="co-time"]').val();
            if(time == '' || !checkTime(time)) {
                iosOverlay({
                    text: '合作时间格式错误',
                    duration: 1000
                });
                return;
            }
            var person = parent.find('[data-role="co-person"]').val();
            if(person == '') {
                iosOverlay({
                    text: '合作客户不能为空',
                    duration: 1000
                });
                return;
            }
            var effect = parent.find('[data-role="co-effect"]').val();
            if(effect == '') {
                iosOverlay({
                    text: '推广效果不能为空',
                    duration: 1000
                });
                return;
            }
            var link = parent.find('[data-role="co-link"]').val();

            var value = successArr[$this.attr('data-success')].getContent();

            if(cid) {
                var tempObj = {
                    name: name,
                    opTime: time,
                    effect: effect,
                    link: link,
                    customer: person,
                    value: value
                }
                obj = {
                    cid: cid,
                    pid: uid,
                    value: JSON.stringify(tempObj)
                }
            } else {
                var tempObj = {
                    name: name,
                    opTime: time,
                    effect: effect,
                    link: link,
                    customer: person,
                    value: value
                }
                obj = {
                    cid: cid,
                    pid: uid,
                    value: JSON.stringify(tempObj)
                }
            }
            $.ajax({
                url: window.domain + window.requestUrl.getEditInfoUrl + '2',
                type: 'post',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                data: obj,
                success: function(res) {
                    if(typeof(res.not_login) != 'undefined') {
                        window.setCookie('go_back_link', window.location.href);
                        window.location.href = './login.html';
                        return;
                    }
                    if(res.status) {
                        iosOverlay({
                            text: '提交成功',
                            duration: 1000
                        });
                    } else {
                        iosOverlay({
                            text: res.msg,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })
        })
    },
    getinfo: function() {
        // 媒体介绍
        $.ajax({
            url: window.domain + window.requestUrl.getEditInfoUrl + '1',
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data: {
                pid: uid
            },
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }
                if(res.status) {
                    if(mediaEdit && res.data.data) {
                        mediaEdit.ready(function() {
                            mediaEdit.setContent(res.data.data, false);
                        })
                    }
                } else {
                    iosOverlay({
                        text: res.msg,
                        duration: 1000
                    });
                }
            },
            error: function(e) {
            }
        })

        // 合作须知
        $.ajax({
            url: window.domain + window.requestUrl.getEditInfoUrl + '3',
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data: {
                pid: uid
            },
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }
                if(res.status) {
                    if(coNotesEdit && res.data.data) {
                        coNotesEdit.ready(function() {
                            coNotesEdit.setContent(res.data.data, false);
                        })
                    }
                } else {
                    iosOverlay({
                        text: res.msg,
                        duration: 1000
                    });
                }
            },
            error: function(e) {
            }
        })
        // 成功案例
        $.ajax({
            url: window.domain + window.requestUrl.getEditInfoUrl + '2',
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data: {
                pid: uid
            },
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }
                if(res.status) {
                    $.each(res.data.data, function(index, item) {
                        var random = Math.random();
                        var tpl = '<div class="mediaLogined-main__success">\
                                    <div class="form-item">\
                                        <span class="form-item__name"><em>*</em>案例事件：</span>\
                                        <input type="text" data-role="name" value="'+item.name+'">\
                                        <span class="tips"></span>\
                                    </div>\
                                    <div class="form-item">\
                                        <span class="form-item__name"><em>*</em>合作时间：</span>\
                                        <input type="text" data-role="co-time" value="'+formatTime(item.opTime)+'">（格式: 2017-03-27）\
                                        <span class="tips"></span>\
                                    </div>\
                                    <div class="form-item">\
                                        <span class="form-item__name"><em>*</em>合作客户：</span>\
                                        <input type="text" data-role="co-person" value="'+item.customer+'">\
                                        <span class="tips"></span>\
                                    </div>\
                                    <div class="form-item">\
                                        <span class="form-item__name"><em>*</em>推广效果：</span>\
                                        <input type="text" data-role="co-effect" value="'+item.effect+'">\
                                        <span class="tips"></span>\
                                    </div>\
                                    <div class="form-item">\
                                        <span class="form-item__name">合作链接：</span>\
                                        <input type="text" data-role="co-link" value="'+item.link+'">\
                                        <span class="tips"></span>\
                                    </div>\
                                    <span class="form-item__name">其他说明：</span>\
                                    <script id="success'+random+'" name="content" type="text/plain">\
                                    </script>\
                                    <div class="form-submit ext-edit" data-role="success-submit" style="clear:both;" data-success="success'+random+'" data-cid="'+item.id+'">\
                                        提交发布\
                                    </div>\
                                    <div class="form-submit  ext-edit" data-role="success-del" data-cid="'+item.id+'">\
                                        删除本条\
                                    </div>\
                                </div>';
                            $('[data-role="success-container"]').append(tpl);
                            successArr['success' + random] = UE.getEditor('success' + random);
                            if(item.value) {
                                successArr['success' + random].ready(function() {
                                    successArr['success' + random].setContent(item.value, false);
                                })
                            }

                    })
                } else {
                    iosOverlay({
                        text: res.msg,
                        duration: 1000
                    });
                }
            },
            error: function(e) {
            }
        })
    },
    editSubmit: function() {
        // 媒体介绍
        $('[data-role="media-submit"]').on('click', function() {
            var content = mediaEdit.getContent();
            $.ajax({
                url: window.domain + window.requestUrl.getEditInfoUrl + '1',
                type: 'post',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                data: {
                    pid: uid,
                    value: content
                },
                success: function(res) {if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }

                    if(res.status) {
                        iosOverlay({
                            text: '提交成功',
                            duration: 1000
                        });
                    } else {
                        iosOverlay({
                            text: res.msg,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })
        })

        // 合作须知
        $('[data-role="cooperation-submit"]').on('click', function() {
            var content = coNotesEdit.getContent();
            $.ajax({
                url: window.domain + window.requestUrl.getEditInfoUrl + '3',
                type: 'post',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                data: {
                    pid: uid,
                    value: content
                },
                success: function(res) {
                    if(typeof(res.not_login) != 'undefined') {
                        window.setCookie('go_back_link', window.location.href);
                        window.location.href = './login.html';
                        return;
                    }
                    if(res.status) {
                        iosOverlay({
                            text: '提交成功',
                            duration: 1000
                        });
                    } else {
                        iosOverlay({
                            text: res.msg,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })
        })
    },
    schedule: function() {
        window.appointment = {}
        $.ajax({
            url: window.domain + window.requestUrl.getEditInfoUrl + '4',
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data: {
                pid: window.getUrlParam('id')
            },
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }
                if(res.status) {
                    var result = res.data.result;
                    $.each(result, function(index, item) {
                        window.appointment[item.dt] = 1;
                    })
                    $('.calendar-nextmonth').trigger('click');
                    $('.calendar-prevmonth').trigger('click');
                } else {
                    iosOverlay({
                        text: res.msg,
                        duration: 1000
                    });
                }
            },
            error: function(e) {
            }
        })
        $('body').append('<script src="assets/jquery.easyui.min.js"></script><script src="assets/jquery.fullcalendar-edit.js"></script>')

    },
    init: function() {
        this.getData();
        this.submit();
        this.editSubmit();
        this.schedule();
    }
}
headline.init();
